import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form, Input, Button, Modal, Row, Col, DatePicker, InputNumber } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data'
import { getPdbIssuanceList, addPdbIssuanceList, updatePdbIssuanceList } from './service'
import TableTitle from '../../../components/TableTitle'
import { getCode } from '@/services/generateCode'

// 日期选择器国际化配置
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

const { RangePicker } = DatePicker;

export default () => {

  // add模态框控制
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  // edit模态框配置
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  // 被修改的数据
  const [upDate, setUpdDate] = useState({})
  // 添加用户数据表单实例
  const [addFormRef] = Form.useForm();
  // 创建的 form 控制实例 用户数据修改表单交互 
  const [editForm] = Form.useForm();

  // 新增按钮事件
  const addInfo = async () => {
    setIsAddModalVisible(true);
    // 获取配置编码
    let res = await getCode({ type: 2 })
    // 表单赋值配置编码
    addFormRef.setFieldsValue({ configDate: moment(new Date), configNo: res.body.code })
  };

  // 确认新增触发事件
  const handleAddOk = () => {
    // 表单验证
    addFormRef.validateFields().then(async () => {
      // 获取新增表单的值
      var response = addFormRef.getFieldsValue()
      // 调用新增接口
      let res = await addPdbIssuanceList({
        ...response,
        effDt: response.date[0].format("YYYY-MM-DD"),
        expDt: response.date[1].format("YYYY-MM-DD"),
        configDate: response.configDate.format("YYYY-MM-DD"),
      })
      console.log(res);
      if (res) {
        // 刷新表格
        actionRef.current?.reload()
        // 重置表单
        addFormRef.resetFields();
        // 关闭模态框
        setIsAddModalVisible(false)
      }
    }).catch((err) => {
      console.log(err);
    })
  }

  // 修改按钮事件
  const edit = (record: any) => {
    setUpdDate(record)
    let {
      effDt,
      expDt,
      totalDailyInvestment,
      configNo,
      configName
    } = record
    let data = {
      date: [moment(effDt), moment(expDt)],
      totalDailyInvestment,
      configNo,
      configName
    }
    setIsEditModalVisible(true)
    // edit模态框的form表单回显数据
    editForm.setFieldsValue(data);
  }
  // 处理修改
  const handleEditOk = () => {
    // 表单验证
    editForm.validateFields().then(async () => {
      // 获取修改表单的值
      var reponse = editForm.getFieldsValue()
      let {
        configName,
        configNo,
        totalDailyInvestment,
        date
      } = reponse
      let data = {
        configName,
        configNo,
        totalDailyInvestment,
        effDt: date[0].format("YYYY-MM-DD"),
        expDt: date[1].format("YYYY-MM-DD"),
      }
      let res = await updatePdbIssuanceList(data)
      if (res) {
        // 重置表单
        editForm.resetFields();
        // 关闭模态框
        setIsEditModalVisible(false)
        // 表格重新渲染
        actionRef.current?.reload()
      }
    }).catch(() => { })
  }

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData

  // 操作行数据 自定义操作行
  // text当前的值,foreach下面的执行完才有值 record当前行的全部数据 inde数组下标
  const action = (text: any, record: any) => {
    // 判断是否可以修改
    return record.status !== 1 ?
      [<a key='action' onClick={() => edit(record)}>修改</a>] :
      null
  }
  // 定义金额单元格
  const amount = (text: any) => {
    let { props } = text
    return [
      <p
        key='amount'
        style={{ textAlign: 'right', margin: 0 }}
      >
        {typeof props.text === 'number' ? props.text.toFixed(6) : null}
      </p>
    ]
  }
  // 自定义数据的表格头部数据
  columns.forEach(item => {
    item.dataIndex === 'action' ? item.render = action : undefined
    item.dataIndex === 'totalDailyInvestment' ? item.render = amount : undefined
  });

  // Table action 的引用，便于自定义触发，为了下面的reload
  const actionRef = React.useRef<ActionType>();
  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title='运营投放' />}
        scroll={{ x: 900 }}
        actionRef={actionRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={
          async params => {
            console.log(params);

            let data = await getPdbIssuanceList({ ...params, pageNum: params.current })
            console.log(data);
            const result = {
              data: data.body.list,
              total: data.body.total,
            }
            return result;
          }
        }
        rowKey="configNo"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        //设置工具栏按钮及事件
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary" onClick={addInfo}>
            新增
          </Button>,
        ]}
      />
      {/* 新增模态框 */}
      <Modal
        title="运营投放配置添加"
        centered
        visible={isAddModalVisible}
        onOk={handleAddOk}
        onCancel={() => setIsAddModalVisible(false)}
        width={700}>
        <Form
          form={addFormRef}
          name="basic"
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          initialValues={{
            remember: true,
          }}
          autoComplete="off"
        >
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="规则编号"
                name="configNo"
              >
                <Input
                  maxLength={20}
                  disabled
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="规则名称"
                name="configName"
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: '不可为空'
                  }
                ]}
              >
                <Input maxLength={20} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="每日投入和平币数量"
                name="totalDailyInvestment"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  }
                ]}
              >
                <InputNumber maxLength={20} style={{ width: '100%' }} precision={2} min={0} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>

            <Col span={8}>
              <Form.Item
                label="配置时间"
                name="configDate"
              >
                <DatePicker disabled style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={16}>
              <Form.Item
                label="发放时间段"
                name="date"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  }
                ]}
              >
                <RangePicker style={{ width: '100%' }}
                  locale={locale}
                  disabledDate={(current) => {
                    return current && current < moment().endOf('day');
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      {/* 修改模态框 */}
      <Modal
        title="和平币发放规则修改"
        centered
        visible={isEditModalVisible}
        onOk={handleEditOk}
        onCancel={() => setIsEditModalVisible(false)}
        getContainer={false}
        width={700}>
        <Form form={editForm}
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
        >
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="规则编号"
                name="configNo"
              >
                <Input maxLength={20} disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="规则名称"
                name="configName"
                rules={[
                  {
                    required: true,
                    whitespace: true,
                    message: '不可为空'
                  }
                ]}
              >
                <Input maxLength={20} disabled={upDate.status === 0 ? true : false} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="每日投入和平币数量"
                name="totalDailyInvestment"
              >
                <InputNumber style={{ width: '100%' }}
                  disabled={upDate.status === 0 ? true : false}
                  precision={2} min={0}
                  maxLength={20}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={16}>
              <Form.Item
                label="发放时间段"
                name="date"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  }
                ]}
              >
                <RangePicker style={{ width: '100%' }}
                  locale={locale}
                  disabled={
                    upDate.status === 0 ?
                      [true, false] :
                      [false, false]
                  }
                  disabledDate={(current) => {
                    return current && current < moment().endOf('day');
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};